package com.huluobo.mvvmdemo1903a.mvvm.view;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.huluobo.mvvmdemo1903a.R;
import com.huluobo.mvvmdemo1903a.mvvm.DataBindingActivity;
import com.huluobo.mvvmdemo1903a.mvvm.viewmodel.LoginViewModel;

/**
 * Created by lc on 2021/11/22.
 */
public class MvvmLoginActivity extends AppCompatActivity {
    private EditText userNameEt, passwordEt;
    private LoginViewModel loginViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mvvm_login);
        userNameEt = findViewById(R.id.user_name_et);
        passwordEt = findViewById(R.id.password_et);
        Button loginBtn = findViewById(R.id.login_btn);
        loginBtn.setOnClickListener(view -> loginViewModel.login(userNameEt.getText().toString(),
                passwordEt.getText().toString()));

        loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        loginViewModel.getIsLoginSuccessful().observe(this, loginObserver);
    }

    private Observer<Boolean> loginObserver = new Observer<Boolean>() {

        @Override
        public void onChanged(Boolean isLoginSuccessful) {
            if (isLoginSuccessful) {
                Toast.makeText(MvvmLoginActivity.this, loginViewModel.getUserName() + "登录成功",
                        Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MvvmLoginActivity.this, DataBindingActivity.class);
                intent.putExtra("username", loginViewModel.getUserName());
                MvvmLoginActivity.this.startActivity(intent);
            } else {
                Toast.makeText(MvvmLoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
            }
        }
    };
}
